package moni.anyou.com.view.utils;

import android.util.Log;
import android.widget.Toast;

import com.google.gson.Gson;

import org.kymjs.aframe.http.KJStringParams;
import org.kymjs.aframe.http.StringCallBack;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Type;

import moni.anyou.com.view.BuildConfig;
import moni.anyou.com.view.config.SysConfig;

/** 原来的代码冗余的有点多 再封装一层 */

/**
 * KJHttp kjh = new KJHttp(); KJStringParams params = new KJStringParams(); //String cmdPara = new
 * ReqPageBean("17", SysConfig.uid, SysConfig.token, "" + pageNo, "" + pageSize).ToJsonString();
 * String cmdPara = "{\"cmd\":\"17\",\"uid\":\"" + SysConfig.uid + "\",\"token\":\"" +
 * SysConfig.token +"\",\"pageNo\":\"" + pageNo + "\",\"pageSize\":\"" + pageSize +"\",\"cid\":\"" +
 * SysConfig.cid + "\"}"; params.put("sendMsg", cmdPara);
 *
 * <p>kjh.urlGet(SysConfig.ServerUrl, params, new StringCallBack() { @Override public void
 * onSuccess(String t) { try { JSONObject jsonObject = new JSONObject(t); int result =
 * Integer.parseInt(jsonObject.getString("result")); totalCount = jsonObject.getInt("totalCount");
 * if (result >= 1) { ResDynamicsBean temp = new Gson().fromJson(t, ResDynamicsBean.class); if
 * (pageNo > 1) { dynamicsItemAdapter.AddDatas(AppTools.getDynamicsItemBean(temp));
 * swipeRefreshLayout.finishLoadmore(); } else { swipeRefreshLayout.finishRefresh();
 * List<ResDynamicsBean.ListBean> bean = new ArrayList<ResDynamicsBean.ListBean>(); bean.add(new
 * ResDynamicsBean.ListBean()); bean.addAll(AppTools.getDynamicsItemBean(temp));
 * dynamicsItemAdapter.setDatas(bean); }
 *
 * <p>} else { AppTools.jumptoLogin(mBaseActivity, result); Toast.makeText(mContext,
 * jsonObject.get("retmsg").toString(), Toast.LENGTH_LONG).show(); } } catch (Exception ex) {
 * Toast.makeText(mContext, "数据请求失败", Toast.LENGTH_LONG).show(); }
 *
 * <p>} @Override public void onFailure(Throwable t, int errorNo, String strMsg) {
 * Toast.makeText(mContext, "网络异常，请稍后再试", Toast.LENGTH_LONG).show();
 *
 * <p>} });
 */
public class KJHttpBuild extends KJStringParams {

  private Object requestBean;
  private int rawID = -1;
  private boolean showToast=true;
  private Listen listen;



  /**指定数据源*/
  public KJHttpBuild setRequestBean(Object requestBean) {
    this.requestBean = requestBean;
    return this;
  }



  public abstract static class Listen<T>{

    private final Type cast;

    public Listen() {
      cast =    ReflectionUtil.getParameterizedTypes(this)[0];;
      Log.d("test",cast.toString());
    }

    public abstract void onSuccessData(String data, T jsonObj);
    public abstract void onFailure(Throwable t, int errorNo, String strMsg);
  }

  public KJHttpBuild() {}

  public void build(Listen<?> listen ) {
    if(listen==null)
    {
      throw new NullPointerException("listen is null");
    }
    setListen(listen);
    org.kymjs.aframe.http.KJHttp kjh = new org.kymjs.aframe.http.KJHttp();


    String rmsg = "";
    KJStringParams params = new KJStringParams();
    if (requestBean != null) {
      rmsg = new Gson().toJson(requestBean);
    }

    Log.d("test",SysConfig.ServerUrl+"?"+"sendMsg="+rmsg);
    params.put("sendMsg", rmsg);

    if (BuildConfig.Debug_DATA && rawID != -1) {
      callback.onSuccess(read(AppcationUtils.getInstance().getResources().openRawResource(rawID),"utf-8"));
      return;
    }
    kjh.urlGet(SysConfig.ServerUrl, params, callback);
  }

  public class Result{
      String result;
      String retmsg;
  }
  public StringCallBack callback =
      new StringCallBack() {
        @Override
        public void onSuccess(String t) {
          Log.d("test","data="+t);
            if(listen==null)
            {
                return;
            }
          try {
//              {"result":"-1","retmsg":""}

            Result result=new Gson().fromJson(t,Result.class);
            if("-1".equals(result.result)){
                listen.onFailure(new RuntimeException("请求错误"),-1,result.retmsg);
                return;
            }
//            int result = Integer.parseInt(jsonObject.getString("result"));
            Log.d("test",t+" "+listen.cast.getClass().toString());

            listen.onSuccessData(t,new Gson().fromJson(t,listen.cast));
//            if (result >= 1) {
//              listen.onSuccessData(t,new Gson().fromJson(t,listen.cast));
//            } else {
//              onFailure(new RuntimeException("数据请求失败"), -1, "数据请求失败");
//            }
          } catch (Exception ex) {
            onFailure(ex, -1, ex.toString());
          }
        }

        @Override
        public void onFailure(Throwable t, int errorNo, String strMsg) {
//          Toast.makeText(
//                  AppcationUtils.getInstance().getBaseContext(), "网络异常，请稍后再试:"+t.toString(), Toast.LENGTH_LONG)
//              .show();
        }
      };


  public KJHttpBuild setListen(Listen listen) {
    this.listen = listen;
    return this;
  }




  public KJHttpBuild setShowToast(boolean showToast) {
    this.showToast = showToast;
    return this;
  }

  public KJHttpBuild testData(int rawID) {
    this.rawID=rawID;
    return this;

  }


  public static String read(InputStream in, String encode) {

    StringBuffer sb = new StringBuffer();
    try {
      BufferedReader br = null;
      if (encode == null) {
        br = new BufferedReader(new InputStreamReader(in));
      } else {

        br = new BufferedReader(new InputStreamReader(in, encode));

      }
      String line = null;
      while ((line = br.readLine()) != null) {
        sb.append(line);
        sb.append("\n");
      }
      br.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
    return sb.toString().trim();
  }



}
